<?php				   
//将添加剂名称，类别，功能，adi值存入food_additive表，返回添加剂的id值
function saveAdditiveInfor($additive_ch_name,$additive_bm,$additive_adi,$additive_func,$dbh)
{
	//查询该添加剂是否已经存在
	$sql = "SELECT `id` FROM `food_additive` WHERE `additive_ch_name` = ? OR `additive_bm` = ?";
	
	$sth = $dbh->prepare($sql) or die("添加剂查重error");
	
	$sth->execute(array("$additive_ch_name","$additive_ch_name"));
	
	$count = $sth->rowCount(); 

	if($count != 0)
	{
	 	$sql = "UPDATE `food_additive` SET  `adi` = '".$additive_adi."',`func` = '".$additive_func."' WHERE `additive_ch_name` = '".$additive_ch_name."' OR `additive_bm`  = '".$additive_ch_name."'";
		
		$dbh->query($sql) or die($dbh->errorInfo()); 
		
		$result = $sth->fetch(PDO::FETCH_ASSOC);
		
		return $result['id'];
	}
/* 	else
	{
		$sql = "INSERT INTO `food_additive` (`id`, `additive_ch_name`, `additive_bm`, `adi`, `func`) VALUES (NULL, '".$additive_ch_name."', '".$additive_bm."', '".$additive_adi."', '".$additive_func."')";
		
		$dbh->query($sql) or die(print_r($dbh->errorInfo()));
		
		return $dbh->lastInsertId();
	

	} */
}


/* function saveAdditiveGanchiInfor($additive_ch_name,$additive_bm,$additive_adi,$additive_func,$dbh)
{
	//查询该添加剂是否已经存在
	$sql = "SELECT `id` FROM `food_additive_ganchi` WHERE `additive_ch_name` = ? OR `additive_bm` = ?";
	
	$sth = $dbh->prepare($sql) or die("添加剂查重error");
	
	$sth->execute(array("$additive_ch_name","$additive_ch_name"));
	
	$count = $sth->rowCount(); 

	if($count == 0)
	{
		$sql = "INSERT INTO `food_additive_ganchi` (`id`, `additive_ch_name`, `additive_bm`, `adi`, `func`) VALUES (NULL, '".$additive_ch_name."', '".$additive_bm."', '".$additive_adi."', '".$additive_func."')";
		
		$dbh->query($sql) or die(print_r($dbh->errorInfo()));
		
		return $dbh->lastInsertId(); 
	}
	else
	{
		$sql = "UPDATE `food_additive_ganchi` SET `additive_ch_name` = '".$additive_ch_name."', `additive_bm` = '".$additive_bm."', `adi` = '".$additive_adi."',`func` = '".$additive_func."' WHERE `additive_ch_name` = '".$additive_ch_name."'";
		
		$dbh->query($sql) or die($dbh->errorInfo());
		
		$result = $sth->fetch(PDO::FETCH_ASSOC);
		
		return $result['id'];

	}
} */


//将类别存入food_additive_category中，返回类别的id
function saveAdditiveCategory($additive_category,$dbh)
{
	//查询该添加剂类别是否已经存在
	$sql = "SELECT `id` FROM `food_additive_category` WHERE `additive_category` = ?";
	
	$sth = $dbh->prepare($sql) or die("类别查重error");
	
	$sth->execute(array("$additive_category")) or die(print_r($dbh->errorInfo()));
	
	$count = $sth->rowCount(); 

	if($count != 0)
	{
		$result = $sth->fetch(PDO::FETCH_ASSOC);
		
		return $result['id']; 
	}
/* 	else
	{
		$sql = "INSERT INTO `food_additive_category` (`id`, `additive_category`) VALUES (NULL, '".$additive_category."')";
		
		$dbh->query($sql) or die("添加类别error");
		
		return $dbh->lastInsertId();

	} */
}

//依据添加剂的id值和类别的id，更新food_additive_category_rel
function saveAdditiveCategoryRel($additive_id,$additive_category_id,$dbh)
{
	$sql = "SELECT `id` FROM `food_additive_category_rel` WHERE `additive_id` = ? AND `additive_category_id` = ? ORDER BY `id` ASC";
	
	$sth = $dbh->prepare($sql) or die('prepare error');
	
	$sth->execute(array("$additive_id","$additive_category_id"))or die('execute error');
	
	$count = $sth->rowCount();
	
	if($count == 0)
	{
		$sql = "INSERT INTO `food_additive_category_rel` (`id`, `additive_id`, `additive_category_id`) VALUES (NULL, '".$additive_id."', '".$additive_category_id."')";
		
		$dbh->query($sql) or die(print_r($dbh->errorInfo()));
	}
}
												
//将添加剂的安全信息存入food_additiv_security表
function saveAdditiveSecurity($additive_id,$security,$dbh)
{
 	$sql = "SELECT `id` FROM `food_additive_security` WHERE `security` = ? ORDER BY `id` ASC";
	
	$sth = $dbh->prepare($sql) or die (print_r($dbh->errorInfo()));
	
	$sth->execute(array("$security"));
	
	$count = $sth->rowCount(); 
	
	if($count == 0)
	{
		$sql = "INSERT INTO `food_additive_security` (`id`,`additive_id`,`security`) VALUES (NULL,'".$additive_id."','".$security."')";
	
		$dbh->query($sql) or die('secu error query');
	}
}

//获取最大使用量的开始键名
function getMaxuseStartKey($maxuse)
{
	foreach($maxuse as $maxk1=>$maxv1)
	{
		if(trim($maxv1) == '二、允许添加进各种食品中的最大使用量' || trim($maxv1) == '三、允许添加进各种食品中的最大使用量')
		{
			return $maxk1;
		}
	}
}

//将食品分类信息存入food_category中
/* function saveFoodCategory($category,$dbh)
{
	$sth = $dbh->prepare("SELECT `id` FROM `food_category` WHERE `category` = ? ORDER BY `id` ASC") or die('error prapare');
	
	$sth->execute(array("$category"));
	
	$count = $sth->rowCount();

	if($count == 0)
	{
		$dbh->query("INSERT INTO `food_category` (`id`, `category`) VALUES (NULL, '".$category."')") or die($dbh->errorInfo());
	
		return $dbh->lastInsertId(); 
	}
	else
	{
		$result = $sth->fetch(PDO::FETCH_ASSOC);
		
		return $result['id'];
	
	}
	
} */

//将添加剂在各类食品中的最大使用量存入food_maxuse
/* function saveMaxuse($additive_id,$category_id,$maxuse,$dbh)
{
	$sth = $dbh->prepare("SELECT `id` FROM `food_maxuse` WHERE `additive_id` = ? AND `category_id` = ? ORDER BY `id` ASC") or die('error prapare');
	
	$sth->execute(array("$additive_id","$category_id"));
	
	$count = $sth->rowCount();

	if($count == 0)
	{
		$dbh->query("INSERT INTO `food_maxuse` (`id`, `additive_id`, `category_id`, `maxuse`) VALUES (NULL, '".$additive_id."','".$category_id."','".$maxuse."')") or die($dbh->errorInfo());
	}
} */

//去除标签
function DeleteHtml($str) 
{  
	$str = strip_tags($str); 
	$str = str_replace("\t","",$str); 
	$str = str_replace("\r\n","",$str); 
	$str = str_replace("\r","",$str); 
	$str = str_replace("\n","",$str); 
	$str = str_replace(" "," ",$str); 
	$str = str_replace("&nbsp;"," ",$str); 
	$str = trim($str);
	
	return trim($str); 
}

//敢吃网数据采集 START
//食品有多少页
function ganchi_getFoodHasHowManyPage($url)
{
	foreach($url as $key=>$value)   
	{   //http://www.ganchi.net/category.php?id=34&page=11&sort=comment_rank&order=DESC
		if (preg_match("/http:\/\/www\.ganchi\.net\/category\.php\?id=[1-9]{1,5}(.*?)order=DESC/i",$value))   
		{   
			$urlPage[$key] = $value;  
		}
	} 
	
	return $urlPage;
}


//食品内容页面
function ganchi_deleteUnlinkUrl($url)
{
	foreach($url as $key=>$value)   
	{   
		if (preg_match("/http:\/\/www\.ganchi\.net\/goods\.php\?id=[1-9]{1,5}/i",$value))   
		{   
			$urlDetail[$key] = $value;  
		}
	} 
	
	return $urlDetail;
}

//合并数组中键值相同的元素
function ganchi_array_multi_unique($ar) 
{
  $ar = array_map('serialize', $ar);
  
  $ar = array_unique($ar);
  
  return array_map('unserialize', $ar);
}

//$newArr = array_unique($urlDetail);

//删除数组空元素
function delArrayRepeat($arr)
{
	if(is_array($arr))
	{
		$arr = array_unique($arr);
		
		foreach($arr as $k=>$v)
		{
			if($v == '')
			{
				unset($arr[$k]);
			}
		}
		
		$result = $arr;
   }
   else
   {
	    $result = "参数必需是数组！";
   }
	
	return $result;
}

//敢吃网基本食物数据录入
function ganchi_saveFoodBasicInfo($titleHandle,$us_category,$brand,$Produce,$dbh)
{
	$sth = $dbh->prepare("SELECT `id` FROM `food_basic` WHERE `ch_name` = ? AND `category_id` = ? AND `brand` = ? ORDER BY `id` ASC") or die($dbh->errorInfo());
	
	$sth->execute(array("$titleHandle","$us_category","$brand"));
	
	$count = $sth->rowCount();

	if($count == 0)
	{
		$dbh->query("INSERT INTO `food_basic` (`id`, `ch_name`, `category_id`,`brand`,`producer`) VALUES (NULL, '".$titleHandle."','".$us_category."','".$brand."','".$Produce."')") or die($dbh->errorInfo());
	
		return $dbh->lastInsertId(); 
	}
	else
	{
		$result = $sth->fetch(PDO::FETCH_ASSOC);
		
		return $result['id'];
	}
}

//存入food_batching表中,返回batching_id.结合food_basic_id,在food_basic_batching_rel建立联系
function ganchi_saveBatchingInfo($batching,$dbh)
{
	$sth = $dbh->prepare("SELECT `id` FROM `food_batching` WHERE `batching` = ? ORDER BY `id` ASC") or die('error prapare');
	
	$sth->execute(array("$batching"));
	
	$count = $sth->rowCount();

	if($count == 0)
	{
		$dbh->query("INSERT INTO `food_batching` (`id`, `batching`) VALUES (NULL, '".$batching."')") or die($dbh->errorInfo());
	
		return $dbh->lastInsertId(); 
	}
	else
	{
		$result = $sth->fetch(PDO::FETCH_ASSOC);
		
		return $result['id'];
	}

}
							
//build relationship
function ganchi_buildRelationshipFoodBatching($dbFoodBasicId,$foodBatching,$dbh)
{
	$sth = $dbh->prepare("SELECT `id` FROM `food_basic_batching_rel` WHERE `basic_id` = ? AND `batching_id` = ? ORDER BY `id` ASC") or die('error prapare');
	
	$sth->execute(array("$dbFoodBasicId","$foodBatching"));
	
	$count = $sth->rowCount();

	if($count == 0)
	{
		$dbh->query("INSERT INTO `food_basic_batching_rel` (`id`, `basic_id`, `batching_id`) VALUES (NULL, '".$dbFoodBasicId."', '".$foodBatching."')") or die($dbh->errorInfo());
	}
}

//判断该添加剂是否为添加剂种类
function getAdditiveExistsCounts($additiveHandle,$dbh)
{
	$sth = $dbh->prepare("SELECT `id` FROM `food_additive_category` WHERE `additive_category` = ? ORDER BY `id` ASC") or die('error prapare');
	
	$sth->execute(array("$additiveHandle"));
	
	return $count = $sth->rowCount();
}

//根据添加剂名查询food_additive表，返回其additive_id
//根据additive_id和basic_id在food_basic_additive_rel表建立食物和添加剂的联系
function ganchi_getDbAdditiveId($additiveHandle,$dbh)
{
	$sth = $dbh->prepare("SELECT `id` FROM `food_additive` WHERE `additive_ch_name` = ? OR `additive_bm` = ? ORDER BY `id` ASC") or die('error prapare');
	
	$sth->execute(array("$additiveHandle","$additiveHandle"));
	
	$count = $sth->rowCount();

	if($count != 0)
	{
		$result = $sth->fetch(PDO::FETCH_ASSOC);
		
		return $result['id'];
		
	}
/* 	else
	{
		$dbh->query("INSERT INTO `food_additive` (`id`, `additive_ch_name`) VALUES (NULL, '".$additiveHandle."')") or die($dbh->errorInfo());
	
		return $dbh->lastInsertId(); 
		
	} */

}


function ganchi_getDbAdditive($additiveHandle,$dbh)
{
	$sth = $dbh->prepare("SELECT `id` FROM `food_additive_ganchi` WHERE `additive_ch_name` = ? OR `additive_bm` = ? ORDER BY `id` ASC") or die('error prapare');
	
	$sth->execute(array("$additiveHandle","$additiveHandle"));
	
	$count = $sth->rowCount();

	if($count == 0)
	{
		$dbh->query("INSERT INTO `food_additive_ganchi` (`id`, `additive_ch_name`) VALUES (NULL, '".$additiveHandle."')") or die($dbh->errorInfo());
	
		return $dbh->lastInsertId(); 
	}
	else
	{
		$result = $sth->fetch(PDO::FETCH_ASSOC);
		
		return $result['id'];
	}

}



							
//rebuild relationship 
function ganchi_buildRelationshipFoodAdditive($dbFoodBasicId,$dbAdditiveId,$dbh)
{
	$sth = $dbh->prepare("SELECT `id` FROM `food_basic_additive_rel` WHERE `basic_id` = ? AND `additive_id` = ? ORDER BY `id` ASC") or die('error prapare');
	
	$sth->execute(array("$dbFoodBasicId","$dbAdditiveId"));
	
	$count = $sth->rowCount();

	if($count == 0)
	{
		$dbh->query("INSERT INTO `food_basic_additive_rel` (`id`, `basic_id`, `additive_id`) VALUES (NULL, '".$dbFoodBasicId."', '".$dbAdditiveId."')") or die($dbh->errorInfo());
	}

}


//将相关营养成分的信息存入food_nutrition表中
function ganchi_saveFoodNutritionInfo($dbFoodBasicId,$nutritionHandleRate,$nutritionHandleName,$nutritionHandleProPortion,$nutritionHandleNrv,$dbh)
{
	$sth = $dbh->prepare("SELECT `id` FROM `food_nutrition` WHERE `basic_id` = ? AND `nutrition_ch_name` = ? ORDER BY `id` ASC") or die('error prapare');
	
	$sth->execute(array("$dbFoodBasicId","$nutritionHandleName"));
	
	$count = $sth->rowCount();

	if($count == 0)
	{
		$dbh->query("INSERT INTO `food_nutrition` (`id`, `basic_id`, `nutrition_ch_name`, `actual_value`, `nrv`, `unit_rate`) VALUES (NULL, '".$dbFoodBasicId."', '".$nutritionHandleName."', '".$nutritionHandleProPortion."', '".$nutritionHandleNrv."', '".$nutritionHandleRate."')") or die($dbh->errorInfo());
	}
}


//
// Function: 获取远程图片并把它保存到本地
//
//
// 确定您有把文件写入本地服务器的权限
//
//
// 变量说明:
// $url 是远程图片的完整URL地址，不能为空。
// $filename 是可选变量: 如果为空，本地文件名将基于时间和日期
// $filepath 必选 文件存储的目录
// 自动生成.

function ganchi_getImages($url,$basicId,$filepath,$dbh) 
{
	if($url==""):return false;endif;
	
	$ext=strrchr($url,".");
	if($ext!=".gif" && $ext!=".jpg"):return false;endif;

	//获取该图片的名称，形式：商品id_图片id_时间戳.jpg
	$sth = $dbh->prepare("SELECT `id`,`pic_num` FROM `food_basic_image` WHERE `basic_id` = ? ORDER BY `id` ASC") or die('error prapare');
	
	$sth->execute(array("$basicId"));
	
	$count = $sth->rowCount();

	if($count == 0)
	{
		$dbh->query("INSERT INTO `food_basic_image` (`id`, `basic_id`, `pic_num`) VALUES (NULL, '".$basicId."', 1)") or die($dbh->errorInfo());
		
		$sth1 = $dbh->prepare("SELECT `pic_num` FROM `food_basic_image` WHERE `basic_id` = ? ORDER BY `pic_num` DESC") or die('error prapare');
	
		$sth1->execute(array("$basicId"));
		
		$result1 = $sth1->fetch(PDO::FETCH_ASSOC);
		
		(int)$picNum = (int)$result1['pic_num'];
		
		$filename = $basicId.'_'.$picNum.$ext;
		
	}else
	{
		$result = $sth->fetch(PDO::FETCH_ASSOC);
		
		(int)$picNum1 = (int)$result['pic_num'] + 1;
		
		$dbh->query("INSERT INTO `food_basic_image` (`id`, `basic_id`, `pic_num`) VALUES (NULL, '".$basicId."', '".$picNum1."')") or die($dbh->errorInfo());
		
		$sth2 = $dbh->prepare("SELECT `pic_num` FROM `food_basic_image` WHERE `basic_id` = ? ORDER BY `pic_num` DESC") or die('error prapare');
	
		$sth2->execute(array("$basicId"));
		
		$result1 = $sth2->fetch(PDO::FETCH_ASSOC);
		
		(int)$picNum = (int)$result1['pic_num'];
		
		$filename = $basicId.'_'.$picNum.$ext;
	
	}
	
	//判断路经是否存在  
    !is_dir($filepath)?mkdir($filepath):null;  
	ob_start();
	readfile($url);
	$img = ob_get_contents();
	ob_end_clean();
	$size = strlen($img);
	$fp2=@fopen($filepath.'/'.$filename, "a");
	fwrite($fp2,$img);
	fclose($fp2);
	
	//图片路径存入数据库中
	$dbh->query("UPDATE `food_basic_image` SET `picture` = '".$filename."'WHERE `basic_id` = '".$basicId."' AND `pic_num` = '".$picNum."'") or die($dbh->errorInfo());
	
	return $filepath.'/'.$filename;
}

//储存评论信息
function ganchi_saveComments($comment,$tip,$basicId,$dbh)
{
	$sth = $dbh->prepare("SELECT `id` FROM `food_basic_comment` WHERE `basic_id` = ? AND `comment` = ? AND `tip` = ? ORDER BY `id` ASC") or die('error prapare');
	
	$sth->execute(array("$basicId","$comment","$tip"));
	
	$count = $sth->rowCount();
	
	if ($count == 0)
	{
		$dbh->query("INSERT INTO `food_basic_comment` (`id`, `basic_id`, `comment`, `tip`) VALUES (NULL, '".$basicId."', '".$comment."', '".$tip."')") or die($dbh->errorInfo());
	}
}


//敢吃网数据采集 END


















?>